import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
import { verifyTokenEdge } from './app/lib/edge-auth';

// 需要认证的路由
const protectedPaths = [
  '/profile',
  '/diet-recommend',
  '/diet-record',
  '/health-advice',
  '/api/user',
  '/api/diet',
  '/api/health'
];

export async function middleware(request: NextRequest) {
  // 调试日志
  console.log('Middleware path:', request.nextUrl.pathname);
  console.log('All Cookies:', request.cookies.getAll());
  console.log('Auth Cookie:', request.cookies.get('auth-token'));

  const path = request.nextUrl.pathname;

  // 如果是 /api/auth 开头的路由，直接放行
  if (path.startsWith('/api/auth/')) {
    return NextResponse.next();
  }

  // 检查是否是需要认证的路由
  const needsAuth = protectedPaths.some(protectedPath => 
    path === protectedPath || path.startsWith(`${protectedPath}/`)
  );

  if (!needsAuth) {
    return NextResponse.next();
  }

  // 验证 token
  const token = request.cookies.get('auth-token')?.value;
  
  // 调试日志
  console.log('Token found:', !!token);
  if (token) {
    console.log('Token value:', token.substring(0, 10) + '...');
  }
  
  if (!token) {
    if (path.startsWith('/api/')) {
      return NextResponse.json({ message: '未授权' }, { status: 401 });
    }
    return NextResponse.redirect(new URL(`/login?redirect=${path}`, request.url));
  }

  try {
    const payload = await verifyTokenEdge(token);
    console.log('Token verified:', !!payload);
    
    if (!payload) {
      throw new Error('Invalid token');
    }
    return NextResponse.next();
  } catch (error) {
    console.error('Token verification failed:', error);
    if (path.startsWith('/api/')) {
      return NextResponse.json({ message: '未授权' }, { status: 401 });
    }
    const response = NextResponse.redirect(new URL(`/login?redirect=${path}`, request.url));
    response.cookies.delete('auth-token');
    return response;
  }
}

// 修改 matcher 配置，包含根路径
export const config = {
  matcher: [
    '/profile',
    '/profile/:path*',
    '/diet-recommend',
    '/diet-recommend/:path*',
    '/diet-record',
    '/diet-record/:path*',
    '/health-advice',
    '/health-advice/:path*',
    '/api/:path*'
  ]
}; 